<template>
	<div class="main-wraper">
		<div class="search-wraper">
			<el-input placeholder="请输入关键词" v-model="searchVal" clearable @clear="searchBtn" class="input-with-select">
				<el-select v-model="searchModel" slot="prepend" placeholder="请选择列">
					<el-option v-for="(item, index) in columnList" :label="item.name" :value="item.key"
						:key="index"></el-option>
				</el-select>
			</el-input>
			<el-button type="primary" class="search-btn" icon="el-icon-search" @click="searchBtn"
				:disabled="uploading">搜索</el-button>
			<el-button-group class="download-btn">
				<el-button type="primary" class="search-btn" icon="el-icon-message" :loading="jobloading"
					:disabled="jobloading || selectionList.length == 0" @click="batchJobBtn('lie')">获取猎头职位</el-button>
				<el-button type="primary" class="search-btn" icon="el-icon-message" :loading="jobloading"
						:disabled="jobloading || selectionList.length == 0" @click="batchJobBtn('all')">获取所选职位</el-button>
				<el-button type="success" class="search-btn" icon="el-icon-download"
					:disabled="selectionList.length == 0" @click="export2Excel" :loading="uploading">导出Excel</el-button>
				
				<el-button type="warning" class="search-btn" icon="el-icon-upload" :disabled="selectionList.length == 0"
					@click="batchExportBtn" :loading="uploading">批量导入系统</el-button>
				
				<el-button type="info" class="search-btn" icon="el-icon-upload" @click="exportBtn"
					:loading="uploading">全部导入系统</el-button>
				<el-button type="danger" class="search-btn" icon="el-icon-delete"
					:disabled="uploading || selectionList.length == 0" @click="batchDeleteBtn()">批量删除</el-button>
			</el-button-group>
			<!-- <el-button type="primary" class="download-btn" icon="el-icon-upload" :loading="uploading"
				@click="exportBtn">导入系统</el-button> -->
		</div>
		<el-table class="excel-table" v-loading="loading || uploading || jobloading" ref="Table" stripe :height="tableHeight"
			:element-loading-text="loadingText||(loading ? '加载中···' : '导入中···')" current-row-key="id" row-key="id" :data="tableData"
			border @selection-change="handleSelectionChange" @sort-change="sortChange" style="width: 100%">
			<el-table-column type="selection" width="55" fixed="left"></el-table-column>
			<el-table-column v-for="(item, index) in columnList" :prop="item.key" :sortable="item.sortable"
				:label="item.name" :width="item.width" :min-width="item.minWidth || '-'" :key="index"
				:formatter="formatterColumn" show-overflow-tooltip :fixed="item.fixed||false">
			</el-table-column>
			<el-table-column width="120" label="来源">
				<template slot-scope="scope">
					<el-tag type="primary" v-if="fromSite == 'liepin'">猎聘</el-tag>
					<el-tag type="primary" v-else-if="fromSite == 'zhipin'">BOSS</el-tag>
					<el-tag type="primary" v-else-if="fromSite == 'zhaopin'">智联</el-tag>
					<el-tag type="primary" v-else>其他</el-tag>
				</template>
			</el-table-column>
			<el-table-column width="100" label="创建人">
				<template slot-scope="scope">
					{{ fromUser }}
				</template>
			</el-table-column>
			<el-table-column width="120" fixed="right" label="操作">
				<template slot-scope="scope">
					<el-button type="danger" size="small" class="delete-btn"
						@click="deleteBtn(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination background :page-sizes="pageSizes" :page-size="pageSize" :current-page="currentPage"
			:pager-count="pagerCount" :total="totalCount" @size-change="handleSizeChange"
			@current-change="handleCurrentChange" layout="total, sizes, prev, pager, next, jumper"></el-pagination>
	</div>
</template>
<script>
	import _ from "underscore";
	import ExcelJS from "exceljs";
	import FileSaver from "file-saver";
	const initList = [{
		"name": "09819F-理赔运营岗",
		"location": "郑州",
		"salary": "8-10k",
		"avatar":"//image0.lietou-static.com/normal/67d77563b0308c76626ca94406u.jpg",
		"companyName": "平安健康保险股份有限公司河南分公司",
		"companyTags": [
			"保险"
		],
		"description":"业务支持专员业务支持专员业务支持专员业务支持专员业务支持专员业务支持专员业务支持专员业务支持专员业务支持专员",
		"companyScale": "50-99人",
		"hr": "师女士",
		"hrjob": "业务支持专员",
		"link": "https://www.liepin.com/job/1976210801.shtml?pgRef=c_pc_search_page%3Ac_pc_search_job_listcard%402_76210801%3A1%3A7add5ede-d744-48b7-81ef-43cf9c937119&d_sfrom=search_prime&d_ckId=null&d_curPage=0&d_pageSize=40&d_headId=null&d_posi=0&skId=mu7mafxrd0hsr80djz8mep54jqybabgb&fkId=mu7mafxrd0hsr80djz8mep54jqybabgb&ckId=mu7mafxrd0hsr80djz8mep54jqybabgb&sfrom=search_job_pc&curPage=0&pageSize=40&index=0"
	}, {
		"name": "09819F-理赔运营岗",
		"avatar":"//image0.lietou-static.com/normal/67d77563b0308c76626ca94406u.jpg",
		"location": "郑州",
		"salary": "面议",
		"companyName": "平安健康保险股份有限公司河南分公司",
		"companyTags": [
			"保险"
		],
		"companyScale": "50-99人",
		"hr": "师女士",
		"hrjob": "业务支持专员",
		"link": "https://www.liepin.com/job/1976210801.shtml?pgRef=c_pc_search_page%3Ac_pc_search_job_listcard%402_76210801%3A1%3A7add5ede-d744-48b7-81ef-43cf9c937119&d_sfrom=search_prime&d_ckId=null&d_curPage=0&d_pageSize=40&d_headId=null&d_posi=0&skId=mu7mafxrd0hsr80djz8mep54jqybabgb&fkId=mu7mafxrd0hsr80djz8mep54jqybabgb&ckId=mu7mafxrd0hsr80djz8mep54jqybabgb&sfrom=search_job_pc&curPage=0&pageSize=40&index=0"
	}];
	var tableData = [];
	var tempTableData = [];

	export default {
		name: "preview",
		components: {},
		data() {
			let that = this;
			return {
				fromSite: "",
				fromUser: "",
				fromUid: "",
				loading: false,
				jobloading: false,
				uploading: false,
				loadingText:'',
				tableHeight: 400,
				searchVal: "",
				searchModel: "",
				columnList: [{
						name: "职位名称",
						key: "name",
						sortable: true,
						width: 200,
						fixed:"left"
					},{
						name: "猎企",
						key: "huntcompanyName",
						sortable: "custom",
						width: 240,
					},{
						name: "HR/顾问",
						key: "hr",
						sortable: true,
						width: 120,
					},{
						name: "职位描述",
						key: "description",
						width: 400,
					},
					{
						name: "HR职位",
						key: "hrjob",
						width: 120,
					},
					{
						name: "工作地点",
						key: "location",
						sortable: true,
						width: 120,
					},
					{
						name: "薪水待遇",
						key: "salary",
						sortable: true,
						width: 120,
					},
					{
						name: "预估年薪（万)",
						key: "salary_year",
						sortable: "custom",
						width: 150,
					},
					{
						name: "公司名称",
						key: "companyName",
						sortable: "custom",
						width: 240,
					},
					{
						name: "公司标签",
						key: "companyTags",
						width: 200,
					},
					{
						name: "公司规模",
						key: "companyScale",
						sortable: true,
						width: 120,
					},
					
					{
						name: "链接",
						key: "link",
						minWidth: 200,
					},
				],
				tableData: [],
				pageSizes: [50, 100, 200, 500],
				pagerCount: 11,
				pageSize: 500,
				currentPage: 1,
				totalCount: 0,
				perCount: 10,
				selectionList: [],
			};
		},
		methods: {
			searchBtn() {
				if (this.searchVal && !this.searchModel) {
					return this.$message({
						message: "请选择左侧要搜索的列",
						type: "warning",
						duration: 2000,
					});
				}
				tableData = tempTableData;
				this.resetTableData();
			},
			formatterColumn(row, column, value, index) {
				const that = this;
				if (column.property == "name") {
					return ( <
						a class = "j_link"
						href = {
							row.link
						}
						target = "_blank" > {
							" "
						} {
							value
						} {
							" "
						} <
						/a>
					);
				}
				if (column.property == "link") {
					return ( <
						a class = "j_link"
						href = {
							value
						}
						target = "_blank" > {
							" "
						} {
							value
						} {
							" "
						} <
						/a>
					);
				}
				if(column.property == "hr"){
					return <div class="hr"><el-avatar size="40" src={row.avatar}></el-avatar>{value}</div>
				}
				if (column.property == "companyTags") {
					let tagName = value;
					if (typeof value == 'string') {
						tagName = [value];
					}
					return tagName && tagName.map((name) => {
						return <el-tag class = "name" > {
							name
						} </el-tag>;
					});
				}
				return value;
			},
			calculateMoney(salary) {
				if (!salary.includes("·") && !salary.toLocaleLowerCase().includes("k"))
					return salary;
				const s = salary.split("·");
				var month = 12;
				if (s.length > 1) {
					const m = parseInt(s[1]);
					if (!isNaN(m)) {
						month = m;
					}
				}
				const money = parseInt(s[0].split("-").pop());
				if (isNaN(money)) {
					return salary;
				}
				return (money * month) / 10;
			},
			batchExportBtn() {
				let that = this;
				this.$confirm(
					`此操作将会把当前选中的${this.selectionList.length}条数据导入到系统内, 是否继续?`,
					"提示", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning",
					}
				).then(() => {
					this.uploadData(this.selectionList);
					//this.uploadTest(this.selectionList)
				});
			},
			exportBtn() {
				let that = this;
				this.$confirm(
					`此操作将会把当前${this.totalCount}条数据导入到系统内, 是否继续?`,
					"提示", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning",
					}
				).then(() => {
					this.uploadData(tableData);
				});
			},
			excelBtn() {

			},
			// uploadTest(list){
			// 	const that = this;
			// 	uni.request({
			// 	  url: 'https://fc-mp-5632fc40-f047-42f3-8072-39dbd210a30e.next.bspapp.com/human-admin/index/upload', //接收请求的API
			// 	  method: 'POST', //接收请求的方式,如果不传默认为GET
			// 	  data: {
			// 		uid: that.fromUid,
			// 		from: that.fromSite,
			// 		list,
			// 	  }, //接收请求的data,不传默认为空
			// 	  //header: header, //接收请求的header
			// 	  success(res) {
			// 		 console.info(res,22222)
			// 	  },
			// 	  fail: (err) => {
			// 		 console.info(err,11111)
			// 	  }
			// 	})
			// },
			uploadData(list) {
				this.uploading = true;
				const that = this;
				const jobs = JSON.parse(JSON.stringify(list));
				let succCount = 0;
				let failCount = 0;
				let succList = [];
				const upload = async () => {
					const s = jobs.splice(0, 10 || that.perCount);
					if (s.length > 0) {
						const response = await that.upload(s);
						if (response.code == 200) {
							that.$message({
								type: "success",
								message: response.message,
							});
							//that.batchDelete(s);
							if (response.count) {
								succCount += response.count;
							}
							succList = succList.concat(s);
						} else if (response.code == 500) { //权限问题
							that.uploading = false;
							that.$message({
								type: "error",
								message: response.message,
							});
							return false;
						} else {
							that.$message({
								type: "error",
								message: response.message,
							});
							failCount += s.length;
						}
						upload();
					} else {
						that.$msgbox({
							type: "success",
							message: `成功导入${succCount} 条数据，${succList.length - succCount}条重复，失败${failCount}条，是否打开CMZC系统企业列表？`,
							showCancelButton:true,
							callback:(evt)=>{
								if(evt=='confirm'){
									window.open('https://cmzc.cc/admin/#/pages/company/parter','_blank');
								}
							}
						});
						//that.batchDelete(succList);

						that.uploading = false;
					}
				};
				upload();
			},
			upload(list) {
				const that = this;
				return new Promise((resolve, reject) => {
					uniCloud.callFunction({
						name: "human-admin",
						data: {
							action: "index/upload",
							data: {
								uid: that.fromUid,
								from: that.fromSite,
								list,
							},
						},
						success({
							result
						}) {
							if (result.code == 200) {
								resolve(result);
							} else {
								resolve(result);
							}
						},
						fail(response) {
							reject({
								code: 500,
								message: "导入数据量过大请求超时",
							});
						},
					});
				});
			},
			deleteBtn(data) {
				this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning",
					})
					.then(() => {
						this.$message({
							type: "success",
							message: "删除成功!",
						});
						const index = tempTableData.findIndex((item) => item.id == data.id);
						tempTableData.splice(index, 1);
						this.resetTableData();
					})
					.catch(() => {
						this.$message({
							type: "info",
							message: "已取消删除",
						});
					});
			},
			clearBtn() {},
			async batchJobBtn(type) {
				this.batchList = this.selectionList.filter(item=>{
					return  !item.description&&(type=='lie'?item.hrjob?.includes('猎头'):true);
				}).map(item => {
					return {
						id: item.id,
						link: item.link
					}
				});
				this.batchCount = this.batchList.length;
				this.jobloading = true;
				this.batchText = '共'+this.batchList.length+'条, ';
				this.sendBatchAction();
				setTimeout(()=>{
					this.sendBatchAction();
				},1200)
				setTimeout(()=>{
					this.sendBatchAction();
				},3800);
				// setTimeout(()=>{
				// 	this.sendBatchAction();
				// },5200);
				// setTimeout(()=>{
				// 	this.sendBatchAction();
				// },6800);
			},
			async sendBatchAction(data) {
				if(data){
					const {id,desc,hunt} = data;
					const index = _.findIndex(this.tableData,{id:parseInt(id)});
					if(index>-1){
						this.tableData[index].description = desc;
						if(hunt&&hunt!=this.tableData[index].companyName){
							this.tableData[index].huntcompanyName = hunt;
						}
					}
					this.batchCount--;
					if(this.batchCount<=0){
						this.jobloading = false;
						this.loadingText = '';
						this.tableData = this.tableData.slice();
						clearTimeout(this.closeTimer);
						return this.$message({
							type: "success",
							message: "获取完成!",
						});
					}
				}
				this.loadingText = this.batchText+'剩余'+this.batchList.length+'条';
				if(this.batchList.length<=0){
					this.jobloading = false;
					return clearTimeout(this.closeTimer);
				}
				const job = this.batchList.shift();
				chrome.tabs.create({
				  url: job.link+'&jobId='+job.id,
				  active: false // 新窗口要打开的网址
				});
				clearTimeout(this.closeTimer);
				this.closeTimer = setTimeout(()=>{
					this.tableData = this.tableData.slice();
					this.jobloading = false;
				},10000);
			},
			batchDeleteBtn() {
				this.$confirm("确认批量删除已选中的数据么?", "提示", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning",
					})
					.then(() => {
						this.$message({
							type: "success",
							message: "删除成功!",
						});
						this.batchDelete(this.selectionList);
					})
					.catch(() => {
						this.$message({
							type: "info",
							message: "已取消删除",
						});
					});
			},
			batchDelete(list = []) {
				list.forEach((select) => {
					const index = tempTableData.findIndex((item) => item.id == select.id);
					tempTableData.splice(index, 1);
				});
				this.resetTableData();
			},
			resetTableData() {
				let that = this;
				if (this.searchVal && this.searchModel) {
					tableData = tempTableData.filter((row) => {
						let model = this.searchModel;
						let value = String(row[model]);
						if (value.includes(this.searchVal.trim())) {
							return true;
						}
						return false;
					});
				} else {
					tableData = tempTableData;
				}
				that.totalCount = tableData.length;
				that.currentPage = 1;
				that.loading = false;
				that.setTableData();
				that.updateCacheTableData();
			},
			sortChange({
				prop,
				order
			}) {
				this.loading = true;
				console.log('开启排序：', prop, order)
				if (order) {
					//如果需要排序
					//     tableData = _.sortBy(tableData, (body) => {
					//       const value = body[prop];
					//       if (prop == "salary_year") {
					//         return String(value).includes("面议") ? 10000 : parseFloat(value);
					//       }else if(prop =="companyName"){
					//  return String(value).
					// }
					//       return value;
					//     });
					tableData = tableData.sort((a, b) => {
						const value1 = a[prop];
						const value2 = b[prop];
						if (prop == "salary_year") {
							const salary1 = String(value1).includes("面议") ? 10000 : parseFloat(value1);
							const salary2 = String(value2).includes("面议") ? 10000 : parseFloat(value2);
							return salary1 - salary2;
							//return String(value).includes("面议") ? 10000 : parseFloat(value);
						} else if (prop == "companyName"||prop=="huntcompanyName") {
							return (value1||'').localeCompare(value2||'', 'zh');
						} else {
							return value1 - value2;
						}
					})
					if (order == "descending") {
						tableData = tableData.reverse();
					}
				} else {
					tableData = tableData;
				}

				this.handleCurrentChange(1);
				this.$nextTick(() => {
					this.loading = false;
				});
			},
			handleSizeChange(size) {
				this.pageSize = size;
				this.setTableData();
			},
			handleCurrentChange(current) {
				this.currentPage = current;
				this.setTableData();
			},
			handleSelectionChange(list) {
				this.selectionList = list;
			},
			setTableData() {
				let that = this;
				let start = (that.currentPage - 1) * that.pageSize;
				let end = start + that.pageSize;
				this.tableData = tableData.slice(start, end);
				this.$nextTick(() => {
					this.$refs.Table.bodyWrapper.scrollTop = 0;
				});
			},
			importTableData(list) {
				let tableList = [];
				if (list && list.length > 0) {
					tableList = list;
				} else {
					const temData = localStorage.getItem("temData");
					if (temData) {
						tableList = JSON.parse(temData);
					}
				}
				tempTableData = tableList.map((item, index) => {
					item.id = index + 1;
					item.salary_year = this.calculateMoney(item.salary);
					item.avatar = item.avatar.includes('http')?item.avatar:'http:'+item.avatar;
					return item;
				}).sort((a, b) => {
					return a.companyName.localeCompare(b.companyName, 'zh')
				});
				this.resetTableData();
			},
			updateCacheTableData() {
				const tempData = JSON.stringify(tempTableData);
				localStorage.setItem("temData", tempData);
			},
			bindChromeEvent() {
				const that = this
				if (process.env.NODE_ENV == 'development') {
					that.importTableData(initList);
				}
				that.fromUser = localStorage.getItem("nickname");
				that.fromUid = localStorage.getItem("uid");
				chrome.runtime?.onMessage.addListener((request, sender, sendResponse) => {
					//console.log("接收到来自爬虫的数据", request);
					if (request.type == "preview") {
						const {
							site,
							uid,
							nickname,
							jobList
						} = request.data;
						that.fromSite = site;
						that.fromUser = nickname;
						localStorage.setItem("nickname", nickname);
						that.fromUid = uid;
						localStorage.setItem("uid", uid);
						that.importTableData(jobList);
						sendResponse();
					}else if(request.type == "jobdetail"){ //获取到职位详情
						//console.log('jobdetail',request);
						sendResponse({
							code:200
						});
						that.sendBatchAction(request.data);
					}
				});
			},
			export2Excel() {
				//console.log('12122，点击导出了')
				const workbook = new ExcelJS.Workbook();
				// 添加工作表，名为sheet1
				const columns = [{
					header: "序号",
					key: "index",
					width: 10
				},{
					header: "猎企",
					key: "huntcompanyName",
					width: 40
				},{
					header: "HR/顾问",
					key: "hr",
					width: 20
				},{
					header: "HR/顾问头像",
					key: "avatar",
					width: 20
				}, {
					header: "HR职位",
					key: "hrjob",
					width: 20
				}, {
					header: "工作地点",
					key: "location",
					width: 20
				}, {
					header: "公司名称",
					key: "companyName",
					width: 40
				}, {
					header: "职位名称",
					key: "name",
					width: 40
				},{
					header: "职位描述",
					key: "description",
					width: 60
				}, {
					header: "预估年薪（万)",
					key: "salary_year",
					width: 20
				}, {
					header: "链接",
					key: "link",
					width: 30
				}, {
					header: "备注",
					key: "desc",
					width: 20
				}];
				const sheet = workbook.addWorksheet('职位列表');
				sheet.columns = columns;
				this.selectionList.forEach((item, index) => {
					item.index = String(index + 1);
					item.desc = ' ';
					//item.avatar = item.avatar.includes('http')?item.avatar:'http:'+item.avatar;
					item.salary_year = String(item.salary_year);
					if (typeof item.companyTags != 'string') {
						item.companyTags = item.companyTags.join('、');
					}
					sheet.addRow(item);
					/* 设置样式*/
					const titleCell = sheet.getRow(1);
					titleCell.alignment = {
						vertical: 'middle'
					};
					titleCell.height = 20;
					titleCell.eachCell((cell) => {
						cell.font = {
							color: {
								argb: '000000'
							}, //颜色为红色
							bold: true, // 字体粗体
							size: 12 // 设置字体大小为18
						};
					});
				})
				// 导出表格文件
				workbook.xlsx.writeBuffer().then((buffer) => {
					let file = new Blob([buffer], {
						type: "application/octet-stream"
					});
					FileSaver.saveAs(file, "职位汇总表.xlsx");
				}).catch(error => console.log('Error writing excel export', error))

			}
		},
		mounted() {
			this.$nextTick(() => {
				this.fromUid = "6690c0913f1a4745aec07325";
				this.fromSite = "liepin";
				//this.importTableData();
			});
		},
		created() {
			this.tableHeight = window.innerHeight - 190;
			this.bindChromeEvent();
		},
	};
</script>
<style lang="scss" scoped>
	.main-wraper {
		/deep/.search-wraper {
			.el-input-group {
				width: 300px;
			}

			.el-select .el-input {
				width: 120px;
			}

			.search-btn {
				margin-left: 0px;
			}

			.import-btn {
				margin-left: 20px;
			}

			.download-btn {
				float: right;
			}
		}

		padding: 20px;
		padding-bottom: 0;
	}

	.main-wraper /deep/ .el-dialog__body {
		font-size: 16px;
	}

	.main-wraper .el-button {
		position: relative;
	}

	.main-wraper .el-tag.name {
		margin: 2px;
		font-size: 12px;
		padding: 0 5px;
		line-height: 24px;
		height: 24px;
	}

	.el-pagination {
		text-align: center;
		padding: 20px 0 10px;

		/deep/ .btn-prev,
		/deep/ .btn-next {
			height: 28px;
			border: none;
		}
	}

	.el-table /deep/ .el-table__empty-block {
		min-height: 300px;
	}

	.el-table /deep/ .j_link {
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
    .el-table /deep/ .cell .hr{
		display: flex;
		align-items: center;
		span{
			margin-right: 5px;
		}
	}
	.excel_btn {
		opacity: 0;
		cursor: pointer;
	}

	.excel-table {
		margin-top: 20px;
	}
</style>